package com.bjfu.service.impl;


import com.bjfu.dto.JudgeRequest;
import com.bjfu.dto.RightsManagementRequest;
import com.bjfu.dto.UpdateAdminInfoRequest;
import com.bjfu.dto.UpdatePasswordDTO;
import com.bjfu.mapper.*;
import com.bjfu.model.*;
import com.bjfu.service.SuperManagerService;
import com.bjfu.utils.Result;
import com.bjfu.utils.ResultCodeEnum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;


@Service
public class SuperManagerServiceImpl implements SuperManagerService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private UserInfoMapper userInfoMapper;
    @Autowired
    private AchievementMapper achievementMapper;
    @Autowired
    private ArticleMapper articleMapper;
    @Autowired
    private ErrorInfoMapper errorInfoMapper;
    @Override
    public Result createTeamAdmin(String username, String password) {
        // 验证输入参数
        if (username == null || password == null) {
            return Result.build(null, ResultCodeEnum.USER_ISNULL);
        }
        /*User existingUser = userMapper.getUserByUsername(username);
        if (existingUser != null) {
            return Result.build(null, ResultCodeEnum.USER_EXISTS);
        }*/
        User user=new User();
        user.setUsername(username);
        user.setPassword(password);
        user.setRole(1);
        user.setStatus(1);//账号已经激活
        user.setRegistrationTime(LocalDateTime.now());
        user.setPermit("00011");//默认权限模板为00011
        // 进行数据库操作：比如创建团队管理员
        if(userMapper.insertUser(user)>0){
            // 3. 创建用户详细信息
            UserInfo userInfo = new UserInfo();
            userInfo.setUserId(user.getUserId());
            userInfo.setName(username); // 姓名可以与用户名相同
            userInfo.setStatus(2); // !!初始状态为待审核,不对，对于团队管理员，应该为已经审核通过
            userInfo.setTeamId(1L);//只有一个团队
            userInfo.setApplyReason("超级管理员添加");
            // userInfo邮箱初始为null
            int infoInserted = userInfoMapper.insertUserInfo(userInfo);
            if (infoInserted <= 0) {
                return Result.build(null, ResultCodeEnum.INSERT_FAILED);//插入个人信息错误
            }
            // 操作成功，返回成功的结果
            return Result.ok(user);
        }else{
            return Result.build(null, ResultCodeEnum.INSERT_FAILED);
        }

    }
    // 删除团队管理员
    @Override
    public Result deleteTeamAdmin(Long userId) {
        User user_delete=userMapper.getUserById(userId);//根据用户ID查到是否有该用户
        if (user_delete == null) {
            return Result.build(null, ResultCodeEnum.USER_NOT_FOUND);
        }else {
            int result = userMapper.deleteUser(userId);
            if (result > 0) {
                return Result.ok(null);
            } else {
                return Result.build(null, ResultCodeEnum.DELETE_FAILED);
            }
        }
    }

    //获取团队管理员的具体信息
    @Override
    public Result getTeamAdminInfo(Long userId) {
        UserInfo userInfo = userInfoMapper.getUserInfoById(userId);
        System.out.println(userInfo);
        if (userInfo != null) {
            return Result.ok(userInfo);
        } else {
            return Result.build(null, ResultCodeEnum.USER_NOT_FOUND);
        }
    }

    @Override
    public Result updateAdminInfo(UpdateAdminInfoRequest updateAdminInfoRequest) {
        UserInfo userInfo=userInfoMapper.getUserInfoById(updateAdminInfoRequest.getUser_id());
        if(userInfo==null){
            return Result.build(null,ResultCodeEnum.USER_NOT_FOUND);//未找到该userID对应的用户
        }
        userInfo.setUserId(updateAdminInfoRequest.getUser_id());          // 用户ID
        userInfo.setTeamId(1L);          // 团队ID
        userInfo.setName(updateAdminInfoRequest.getName());              // 姓名
        userInfo.setAvatarUrl(updateAdminInfoRequest.getAvatar_url());    // 头像URL
        userInfo.setResearchField(updateAdminInfoRequest.getResearch_field()); // 研究方向
        userInfo.setStatus(2);          // 状态!!这里是已审核
        userInfo.setApplyReason(updateAdminInfoRequest.getApply_reason());
        userInfo.setBio(updateAdminInfoRequest.getBio());                // 个人简介
        userInfo.setEmail(updateAdminInfoRequest.getEmail());
        System.out.println(userInfo);
        int result = userInfoMapper.updateUserInfo(userInfo);
        // 调用 UserInfoMapper 更新用户信息
        // 判断更新是否成功，返回结果
        if (result > 0) {
            return Result.ok(userInfo);  // 如果更新成功，返回成功的响应
        } else {
            return Result.build(null, ResultCodeEnum.UPDATE_FAILED);  // 更新失败，返回失败的响应
        }
        /*// 创建一个 UserInfo 对象，并填充更新的信息
        UserInfo userInfo = new UserInfo();
        userInfo.setUserId(updateAdminInfoRequest.getUser_id());          // 用户ID
        userInfo.setTeamId(updateAdminInfoRequest.getTeam_id());          // 团队ID
        userInfo.setName(updateAdminInfoRequest.getName());              // 姓名
        userInfo.setAvatarUrl(updateAdminInfoRequest.getAvatar_url());    // 头像URL
        userInfo.setResearchField(updateAdminInfoRequest.getResearch_field()); // 研究方向
        *//*userInfo.setStatus(1);          // 状态,默认为已经激活*//*
        userInfo.setStatus(2);          // user_info状态,默认为已经激活
        userInfo.setBio(updateAdminInfoRequest.getBio());                // 个人简介
        userInfo.setApplyReason(updateAdminInfoRequest.getApply_reason());
        userInfo.setEmail(updateAdminInfoRequest.getEmail());

        System.out.println(userInfo);
        //首先确认用户名是否修改，若修改用户名，则user表中的用户名也需要修改。
        int result = userInfoMapper.updateUserInfo(userInfo);
        *//*User old_user=userMapper.getUserById(updateAdminInfoRequest.getUser_id());
        String new_name=updateAdminInfoRequest.getName();
        String username=old_user.getUsername();
        if(!new_name.equals(username)){
            User new_user=old_user;
            new_user.setUsername(new_name);
            userMapper.updateUser(new_user);
        }*//*
        // 调用 UserInfoMapper 更新用户信息
        // 判断更新是否成功，返回结果
        if (result > 0) {
            return Result.ok(userInfo);  // 如果更新成功，返回成功的响应
        } else {
            return Result.build(null, ResultCodeEnum.UPDATE_FAILED);  // 更新失败，返回失败的响应
        }*/

    }

    //审核成果
    @Override
    public Result judgeAchievement(JudgeRequest judgeRequest) {
        System.out.println("Achievement ID: " + judgeRequest.getAchievement_id());
        System.out.println("Pass Status: " + (judgeRequest.getPass_status() ? 2 : 3));
        // 调用Mapper方法审核科研成果
        int result = achievementMapper.judgeAchievement(judgeRequest.getAchievement_id(), judgeRequest.getPass_status()?2:3);
        if (result > 0) {
            if(judgeRequest.getPass_status()) {
                return Result.ok(judgeRequest);
            }else{
                /*ErrorInfo errorInfo=new ErrorInfo();
                errorInfo.setType(1);//不通过类型为成果，1
                errorInfo.setTypeId(judgeRequest.getAchievement_id());
                errorInfo.setCause(judgeRequest.getRefuse_cause());
                errorInfoMapper.insertErrorInfo(errorInfo);*/
                List<ErrorInfo>errorInfos=errorInfoMapper.getErrorInfoByTypeIdAndType(judgeRequest.getAchievement_id(),1);
                if(errorInfos!=null&&!errorInfos.isEmpty()){
                    String cause=judgeRequest.getRefuse_cause();
                    Long errorId=errorInfos.get(0).getId();
                    errorInfoMapper.updateErrorInfoCause(cause, errorId);
                }
                else {
                    ErrorInfo errorInfo = new ErrorInfo();
                    errorInfo.setType(1);  // 不通过类型为1
                    errorInfo.setTypeId(judgeRequest.getAchievement_id());
                    errorInfo.setCause(judgeRequest.getRefuse_cause());
                    errorInfoMapper.insertErrorInfo(errorInfo);
                }
                return Result.build(judgeRequest,ResultCodeEnum.JUDGE_REFUSED);
            }
        } else {
            return Result.build(null,ResultCodeEnum.UPDATE_FAILED);
        }
    }
    //审核文章
    @Override
    public Result judgeArticle(JudgeRequest judgeRequest) {
        // 调用Mapper方法审核文章
        int result = articleMapper.judgeArticle(judgeRequest.getArticle_id(), judgeRequest.getPass_status()?2:3);
        if (result > 0) {
            if(judgeRequest.getPass_status()) {
                return Result.ok(judgeRequest);
            }else{
               /* //若不通过写入拒绝理由
                ErrorInfo errorInfo=new ErrorInfo();
                errorInfo.setType(2);//不通过类型为文章，2
                errorInfo.setTypeId(judgeRequest.getArticle_id());
                errorInfo.setCause(judgeRequest.getRefuse_cause());
                errorInfoMapper.insertErrorInfo(errorInfo);
                return Result.build(judgeRequest,ResultCodeEnum.JUDGE_REFUSED);*/
                List<ErrorInfo>errorInfos=errorInfoMapper.getErrorInfoByTypeIdAndType(judgeRequest.getArticle_id(),2);
                if(errorInfos!=null&&!errorInfos.isEmpty()){
                    String cause=judgeRequest.getRefuse_cause();
                    Long errorId=errorInfos.get(0).getId();
                    errorInfoMapper.updateErrorInfoCause(cause, errorId);
                }
                else {
                    ErrorInfo errorInfo = new ErrorInfo();
                    errorInfo.setType(2);  // 不通过类型为2
                    errorInfo.setTypeId(judgeRequest.getArticle_id());
                    errorInfo.setCause(judgeRequest.getRefuse_cause());
                    errorInfoMapper.insertErrorInfo(errorInfo);
                }
                return Result.build(judgeRequest,ResultCodeEnum.JUDGE_REFUSED);
            }
        } else {
            return Result.build(null,ResultCodeEnum.UPDATE_FAILED);
        }
    }
    //设置管理员权限
    @Override
    public Result manageRights(RightsManagementRequest rightsManagementRequest) {
        int result = userMapper.updateUserPermissions(rightsManagementRequest.getUser_id(), rightsManagementRequest.getPermit());
        if (result > 0) {
            return Result.ok(null);
        } else {
            return Result.build(null,ResultCodeEnum.UPDATE_FAILED);
        }
    }

    @Override
    public Result getAllTeamAdmins() {
        if(userMapper.getAllTeamAdmins()!=null){
            return Result.ok(userMapper.getAllTeamAdmins());
        }
        else{
            return Result.build(null,ResultCodeEnum.USER_NOT_FOUND);
        }
    }

    @Override
    public Result showAchievementNotJudge() {
        List<Achievement> achievements = achievementMapper.getAchievementsNotJudged();
        if(achievements != null && !achievements.isEmpty()){
            return Result.ok(achievements);
        }
        else{
            return Result.build(null,ResultCodeEnum.ACHIEVEMENT_NOT_FOUND);
        }
    }

    @Override
    public Result showArticleNotJudge() {
        List<Article> articles = articleMapper.getArticlesNotJudged();
        if(articles != null && !articles.isEmpty()){
            return Result.ok(articles);
        }
        else{
            return Result.build(null,ResultCodeEnum.ARTICLE_NOT_FOUND);
        }
    }

    //更改密码
    @Override
    public Result updatePassword(UpdatePasswordDTO updatePasswordDTO) {
        if(userMapper.getUserById(updatePasswordDTO.getUser_id())==null){
            return Result.build(null,ResultCodeEnum.USER_NOT_FOUND);
        }
        int result= userMapper.updatePassword(updatePasswordDTO.getUser_id(), updatePasswordDTO.getPassword());
        if(result>0){
            return Result.ok(updatePasswordDTO);
        }
        else{
            return Result.build(null,ResultCodeEnum.UPDATE_FAILED);
        }
    }

    @Override
    public Result forbiddenAdmin(Long userId) {
        if(userMapper.getUserById(userId)==null){
            return Result.build(null,ResultCodeEnum.USER_NOT_FOUND);
        }
        if(userMapper.judgeMember(userId,4)>0){
            return Result.ok(null);
        }
        return Result.build(null,ResultCodeEnum.UPDATE_FAILED);
    }
}